// [验收版] -- 工单分配
<template>
  <view class="assignment-main">
    <nav-bar class="header" back title="工单分配" @goBack="goBack" />
    <view class="main-container">
      <!--工单基本信息-->
      <van-form ref="infoForm">
        <view class="task-info-container">
          <van-cell-group>
            <van-field v-model="taskName" label="工单名称" placeholder="工单名称" readonly input-align="right" />
            <van-field v-model="taskSiteName" label="作业站点" placeholder="站点名称" readonly input-align="right" />
            <van-field v-model="beginTime" name="beginTime" label="计划开始时间"  placeholder="选择计划开始时间" input-align="right" right-icon="arrow" required error-message-align="right"
              @click="onOpenPicker('beginTime')" :rules="[{ required: true, trigger:'onChange'}]" />
            <van-field v-model="endTime" name="endTime" label="计划结束时间"  placeholder="选择计划结束时间" input-align="right" right-icon="arrow" required error-message-align="right"
              @click="onOpenPicker('endTime')" :rules="[{ required: true, trigger:'onChange'}]" />
            <van-field v-model="operaterText" label="作业人员" placeholder="作业人员" readonly input-align="right" />
            <!-- <van-field v-model="operaterText" disabled label="作业人员" name="operaterText" required clearable 
              clear-trigger="always" placeholder="选择作业人员" input-align="right" right-icon="arrow"
              error-message-align="right" :rules="[{ required: true, trigger:'onSubmit'}]" @click-right-icon="handleSelectUser('operater')" /> -->
          </van-cell-group>
        </view>
        <!--工单分配-->
        <view class="task-assignment-container">

          <view class="task-assignment-item">
            <van-field  name="isCar" label="是否用车" center required icon-prefix="toutiao" left-icon="shouji" style="position:relative;">
              <template #right-icon>
                <van-radio-group v-model="isCar" direction="horizontal">
                  <van-radio name="1">是</van-radio>
                  <van-radio name="0">否</van-radio>
                </van-radio-group>
              </template>
            </van-field>
            <template v-if="isCar==1">
              <van-field v-model="workCarNum" label="作业车辆" placeholder="请输入" :rules="[{ required: true, trigger:'onChange'}]" required input-align="right" />
              <van-field v-model="beginTime1" name="beginTime1" label="开始时间"  placeholder="选择开始时间" input-align="right" right-icon="arrow" required error-message-align="right"
                @click="onOpenPicker('beginTime1')" :rules="[{ required: true, trigger:'onChange'}]" />
              <van-field v-model="endTime1" name="endTime1" label="结束时间"  placeholder="选择结束时间" input-align="right" right-icon="arrow" required error-message-align="right"
                @click="onOpenPicker('endTime1')" :rules="[{ required: true, trigger:'onChange'}]" />
            </template>
        
          </view>
         
        </view>

        <!-- 备注 -->
        <view class="remark-info-container">
          <view>备注</view>
          <van-divider dashed />
          <div class="remark-wrap">
            <textarea class="remark-text" placeholder="" v-model="remark"></textarea>
          </div>
        </view>

        <van-button block @click="submit">提交</van-button>
      </van-form>
      <!--时间选择器-->
      <van-popup v-model="showPicker" position="bottom">
        <van-datetime-picker type="datetime" :formatter="pickerFormatter" cancel-button-text="清空" @confirm="onDatetimeConfirm" @cancel="onDatetimeEmpty" v-model="currentDate" :min-date="minDate" />
      </van-popup>
      <van-popup v-model="showSelectUser" position="right">
        <selectUser :equIds="operaterIds" :selected.sync="staffList" @cancel="onSelUserCancel" />
      </van-popup>
    </view>

  </view>
</template>

<script>
import navBar from '../../../components/common/nav-bar'
import plateTitle from '../../../components/business/plateTitle'
import selectUser from '../common/selectUser'
import { mapGetters } from 'vuex'
import moment from 'moment'
import { Dialog, Toast } from 'vant'
import { number } from 'echarts'

export default {
  components: { navBar, plateTitle, selectUser },
  data() {
    return {
      iconEquUrl: require('../../../static/img/equipment.png'),
      iconCableUrl: require('../../../static/img/opticalCable.png'),
      iconPowerUrl: require('../../../static/img/powerSupply.png'),

      taskName: '',
      taskSiteName: '',
      beginTime: '',
      endTime: '',
      isCar: '1',
      remark: '',
      workCarNum: '',
      beginTime1: '',
      endTime1: '',
      tourOperListName: '',
      tourOperListText: '',

      showPicker: false,
      showSelectUser: false,
      pickerType: '',
      currentDate: '',
      minDate: new Date(0),
      // maxDate: new Date(new Date().setFullYear(new Date().getFullYear() + 10)),
      activeName: ['equipment', 'opticalCable', 'powerSupply'],
      objId: '',

      operaterIds: [],  // 作业人员人员 
      operaterText: '',
      staffList: {
        ids: [],
        text: ''
      },
      staffType: '0'
    }
  },
  onLoad(e) {
    console.log(e.planStartTim, 111)
    this.taskName = e.name
    this.taskSiteName = e.taskSiteName
    // 计划开始时间和结束时间
    this.beginTime = !e.planStartTim
      ? ''
      : moment(e.planStartTim).format('YYYY-MM-DD HH:mm')
    this.endTime = !e.planEndTim
      ? ''
      : moment(e.planEndTim).format('YYYY-MM-DD HH:mm')
    this.objId = e.objId

    this.operaterText = this.userData.userName
  },
  computed: {
    ...mapGetters(['userData'])
  },
  watch: {
    staffList: {
      handler: function (newVal) {
        let staffIdsType = this.staffType + 'Ids'  // operaterIds
        let staffTextType = this.staffType + 'Text'   // operaterText

        this[staffIdsType] = newVal.ids
        this[staffTextType] = newVal.text
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    validator(val) {
      console.log(val)
      // return val ? false : true
    },
    onSelUserCancel() {
      this.showSelectUser = false
    },
    handleSelectUser(t) {
      this.showSelectUser = true
      this.staffType = t
      console.log('12122', this.operaterIds)
      if (this.staffType == 'operater') {
        // 作业人员
        this.staffList = {
          ids: !this.operaterText ? [] : this.operaterIds,
          text: this.operaterText
        }
      }
    },
    onOpenPicker(pickerType) {
      if (pickerType === 'beginTime') {
        this.currentDate =
          this.beginTime !== '' ? new Date(this.beginTime) : new Date()
      } else if (pickerType === 'endTime') {
        this.currentDate =
          this.endTime !== '' ? new Date(this.endTime) : new Date()
      } else if (pickerType === 'beginTime1') { 
        this.currentDate =
          this.beginTime1 !== '' ? new Date(this.beginTime1) : new Date()
      } else if (pickerType === 'endTime1') {
        this.currentDate =
          this.endTime1 !== '' ? new Date(this.endTime1) : new Date()
      }
      this.pickerType = pickerType
      this.showPicker = true
    },
    onDatetimeConfirm(time) {
      let timeString = moment(time).format('YYYY-MM-DD HH:mm')
      if (this.pickerType === 'beginTime') {
        this.beginTime = timeString
        if (
          this.endTime !== '' &&
          new Date(this.endTime).getTime() < new Date(this.beginTime).getTime()
        ) {
          Dialog.alert({
            message: '计划开始时间不可晚于计划结束时间',
            theme: 'round-button'
          })
          this.beginTime = ''
        }
        // this.minDate = new Date(time);
        // this.maxDate = new Date(new Date().setFullYear(new Date().getFullYear() + 10));
      } else if (this.pickerType === 'endTime') {
        this.endTime = timeString
        if (
          this.beginTime !== '' &&
          new Date(this.endTime).getTime() < new Date(this.beginTime).getTime()
        ) {
          Dialog.alert({
            message: '计划结束时间不可早于计划开始时间',
            theme: 'round-button'
          })
          this.endTime = ''
        }
        // this.minDate = new Date(0);
        // this.maxDate = new Date(time);
      } else if (this.pickerType === 'beginTime1') {
        this.beginTime1 = timeString
        if (
          this.endTime1 !== '' &&
          new Date(this.endTime1).getTime() < new Date(this.beginTime1).getTime()
        ) {
          Dialog.alert({
            message: '用车开始时间不可晚于用车结束时间',
            theme: 'round-button'
          })
          this.beginTime1 = ''
        }
        // this.minDate = new Date(0);
        // this.maxDate = new Date(time);
      } else if (this.pickerType === 'endTime1') {
        this.endTime1 = timeString
        if (
          this.beginTime1 !== '' &&
          new Date(this.endTime1).getTime() < new Date(this.beginTime1).getTime()
        ) {
          Dialog.alert({
            message: '用车结束时间不可早于用车开始时间',
            theme: 'round-button'
          })
          this.endTime1 = ''
        }
        // this.minDate = new Date(0);
        // this.maxDate = new Date(time);
      }
      this.showPicker = false
    },
    onDatetimeEmpty() {
      this.showDatetimePicker = false
      this.pickerType === 'beginTime' && (this.beginTime = '')
      this.pickerType === 'endTime' && (this.endTime = '')
    },
    pickerFormatter(type, val) {
      if (type === 'year') return val + '年'
      if (type === 'month') return val + '月'
      if (type === 'day') return val + '日'
      if (type === 'hour') return val + '时'
      if (type === 'minute') return val + '分'
    },
    goBack() {
      uni.navigateTo({
        url: `/pages/acceptanceVersion/orderList/index?status=non-receive`
      })
    },
    async submit() {
      await this.$refs.infoForm
        .validate()
        .then(() => {
          Dialog.confirm({
            message: "是否确认提交？提交后内容不可修改",
          }).then(() => {
            /* 跳转到 工单领取 */
            let parasm = {
              objId: this.objId,

              planStartTim: moment(this.beginTime).format("YYYY-MM-DD HH:mm:ss"),
              planEndTim: moment(this.endTime).format("YYYY-MM-DD HH:mm:ss"),
              operId: this.userData.userId,
              operName: this.userData.userName,
              // orgId: this.userData.orgId,
              // batchId: this.userData.batchId,
              // equIds: this.equIds, // 通信设备人员id
              remark: this.remark,
              useCarStartTime: this.beginTime1?moment(this.beginTime1).format("YYYY-MM-DD HH:mm:ss"):'',
              useCarEndTime: this.endTime1?moment(this.endTime1).format("YYYY-MM-DD HH:mm:ss"):'',
              isCar: Number(this.isCar),
              workCarNum: this.workCarNum,
           
              tourOperListName: this.operaterText,
              // tourOperListText: '',
              taskState: '2',
              taskStateName: '未完成'
            };
            this.$apiRequest.ysbApi.receiveAutumnInspectionTask(parasm).then(res => {
              if (res.msg === "操作成功") {
                Toast.success({
                  message: '领取成功',
                  onOpened: () => {
                    uni.navigateTo({
                      url: "/pages/acceptanceVersion/orderList/index"
                    });
                  }
                });
              } else {
                Toast.fail("领取失败");
              }
            });
          }).catch(() => {})
        })
        .catch(() => {
          Toast('请完善内容')
        })
    }
  }
}
</script>

<style scoped lang="scss">
.assignment-main {
  height: 100vh;
  background-color: #f8f8f8;
  overflow: hidden;
  .header {
    position: sticky;
    top: 0;
    z-index: 9;
  }
  .main-container {
    height: calc(100vh - #{px2vh(193)});
    //min-height: calc(100vh - #{px2vh(283)});
    padding: px2vh(30) px2vw(30) 0 px2vw(30);
    //background-color: #f8f8f8;
    overflow: auto;
    /deep/.van-field {
      .van-field__label,
      .van-field__control:read-only {
        // font-size: px2vw(42);
        color: #323233;
        -webkit-text-fill-color: #323233;
      }
      .van-field__right-icon {
        color: #bebebe;
      }
    }

    .task-info-container,
    .task-assignment-item {
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #ffffff;
    }

    .plate-title {
      margin-top: px2vh(60);
      margin-bottom: px2vh(27);
    }

    .task-assignment-container {
      margin-top: px2vh(30);

      .task-assignment-item {
        margin-bottom: px2vh(30);
        /deep/ .van-collapse-item__content {
          padding: 0;
        }
        /deep/.van-cell--large .van-cell__title {
          font-size: px2vw(42);
        }
        /deep/.van-cell__left-icon {
          height: auto;
          line-height: 100%;

          .van-icon__image {
            width: px2vw(60);
            height: px2vw(60);
            vertical-align: middle;
          }
        }
        /deep/.van-cell__left-icon {
          margin-right: px2vw(20);
        }
      }
    }

    .remark-info-container {
      padding: px2vh(70) px2vw(50);
      font-size: px2vw(42);
      color: #666666;
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #ffffff;
      margin-top: px2vh(40);
      .remark-wrap {
        background-color: #fafafa;
        padding: px2vh(41) px2vw(56) px2vh(77) px2vw(55);
        border-radius: px2vw(20);
        .remark-text {
          height: px2vh(150);
        }
      }
    }
  }
  .van-button {
    // margin-top: px2vh(50);
    height: px2vh(100);
    width: calc(100vw - #{px2vw(60)});
    margin: px2vh(50) auto;
    color: #fff;
    background-color: #417adc;
    border: 1px solid #417adc;
    border-radius: px2vh(60);
  }
}
</style>